/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OtcPublishAdsPresenter.java
 *   @Date: 19-2-28 上午11:55
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.presenter;

import android.text.TextUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.bhex.app.R;
import io.bhex.app.base.AppUI;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.otc.OtcAdsApi;
import io.bhex.sdk.otc.OtcApi;
import io.bhex.sdk.otc.OtcConstant;
import io.bhex.sdk.otc.OtcUserApi;
import io.bhex.sdk.otc.bean.OtcConfigResponse;
import io.bhex.sdk.otc.bean.OtcLastPriceRequestBean;
import io.bhex.sdk.otc.bean.OtcLastPriceResponse;
import io.bhex.sdk.otc.bean.OtcPublishAdResponse;
import io.bhex.sdk.otc.bean.OtcUserInfo;
import io.bhex.sdk.otc.bean.TradeFeeRateBean;
import io.bhex.sdk.trade.AssetApi;
import io.bhex.sdk.trade.TradeApi;
import io.bhex.sdk.trade.bean.AssetDataResponse;
import io.bhex.sdk.trade.bean.AssetListResponse;

public class OtcPublishAdsPresenter extends BasePresenter<OtcPublishAdsPresenter.OtcPublishAdsUI> {
    private Timer timer;
    private TimerTask timerTask;
    private OtcConfigResponse.TokenBean defaultTokenBean;
    private HashMap<String, OtcConfigResponse.TokenBean> symbolMap = new HashMap<>();
    private HashMap<String, OtcConfigResponse.CurrencyBean> currencyMap = new HashMap<>();
    //法币id
    private String currencyId = "";
    private OtcConfigResponse.TokenBean currentTokenBean;
    private OtcUserInfo currentOtcUserInfo;

    public interface OtcPublishAdsUI extends AppUI {
        void showCurrency(OtcConfigResponse.CurrencyBean currencyBean);

        void showCurrentToken(OtcConfigResponse.TokenBean defaultSymbolBean);

        void showConfigInfo(OtcConfigResponse response);

        void showIndexPrice(OtcLastPriceResponse response, OtcConfigResponse.TokenBean symbolBean, String currencyId);

        void updateAssettByToken(OtcConfigResponse.TokenBean tokenBean, String free);

        void showOtcUserInfo(OtcUserInfo response);

        void setCurrentConfig(OtcConfigResponse response);

        boolean getIsBuyOrSell();
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, OtcPublishAdsUI ui) {
        super.onUIReady(activity, ui);
        getOtcUserInfo();
    }

    /**
     * 获取Otc用户信息
     */
    private void getOtcUserInfo() {
        if (!UserInfo.isLogin()) {
            return;
        }
        OtcUserApi.getOtcUserInfo(new SimpleResponseListener<OtcUserInfo>() {
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcUserInfo response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    currentOtcUserInfo = response;
                    getUI().showOtcUserInfo(response);
                    getOtcConfig();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        startTimer();
    }

    @Override
    public void onPause() {
        super.onPause();
        stopTimer();
    }

    private void startTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (currentTokenBean != null) {
                    getLastPrice(currentTokenBean);
                } else {
                    getOtcConfig();
                }
            }
        };
        timer.schedule(timerTask, OtcConstant.TIMER_DELAY, OtcConstant.TIMER_PERIOD);

    }

    private void stopTimer() {
        if (timerTask != null) {
            timerTask.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    private void getOtcConfig() {
        OtcApi.getConfig(new SimpleResponseListener<OtcConfigResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcConfigResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    getUI().setCurrentConfig(response);
                    handleConfigData(response);
                    getUI().showConfigInfo(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    private void handleConfigData(OtcConfigResponse otcConfig) {
        Map<String, TradeFeeRateBean> feeMap = otcConfig.getTradeFeeRate();

        List<OtcConfigResponse.TokenBean> tokenBeanList = otcConfig.getToken();
        //交易币种
        symbolMap.clear();
        if (feeMap != null && tokenBeanList != null && tokenBeanList.size() > 0) {
            for (OtcConfigResponse.TokenBean tokenBean : tokenBeanList) {
                symbolMap.put(tokenBean.getTokenId(), tokenBean);
                tokenBean.setFee(feeMap.get(tokenBean.getTokenId()));
            }
            defaultTokenBean = tokenBeanList.get(0);
            getUI().showCurrentToken(defaultTokenBean);
        }

        //支付的法币
        currencyMap.clear();
        List<OtcConfigResponse.CurrencyBean> currencyList = otcConfig.getCurrency();
        if (currencyList != null && currencyList.size() > 0) {

            for (int i = 0; i < currencyList.size(); i++) {
                OtcConfigResponse.CurrencyBean currencyBean = currencyList.get(i);
                if (currencyBean != null) {
                    String mCurrencyId = currencyBean.getCurrencyId();
                    if (i == 0) {
//                        this.currencyId = mCurrencyId;
                        getUI().showCurrency(currencyBean);
                    }
                    //通过用户信息currency判断默认法币
                    if (currentOtcUserInfo != null) {
                        String currency = currentOtcUserInfo.getCurrency();
                        if (!TextUtils.isEmpty(currency)) {
                            if (currency.equals(mCurrencyId)) {
                                currencyId = currency;
                                getUI().showCurrency(currencyBean);
                            }
                        }
//                        }
                    }

                    currencyMap.put(mCurrencyId, currencyBean);
                }

            }
        }

        if (defaultTokenBean != null) {
            currentTokenBean = defaultTokenBean;
            switchToken(currentTokenBean);
        }
    }

    /**
     * 切换币种
     *
     * @param tokenBean
     */
    public void switchToken(OtcConfigResponse.TokenBean tokenBean) {
        currentTokenBean = tokenBean;
        getLastPrice(tokenBean);
        getAssetList(tokenBean);
        getAsset(tokenBean);
    }

    /**
     * 获取最新价-指数价格
     *
     * @param tokenBean
     */
    private void getLastPrice(final OtcConfigResponse.TokenBean tokenBean) {
        OtcLastPriceRequestBean otcLastPriceRequestBean = new OtcLastPriceRequestBean();
        otcLastPriceRequestBean.token_id = tokenBean.getTokenId();
        otcLastPriceRequestBean.currency_id = currencyId;
        otcLastPriceRequestBean.side = getUI().getIsBuyOrSell() ? 0 : 1;
        OtcApi.getLastPrice(otcLastPriceRequestBean, new SimpleResponseListener<OtcLastPriceResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcLastPriceResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    getUI().showIndexPrice(response, tokenBean, currencyId);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 获取资产列表
     *
     * @param tokenBean
     */
    protected synchronized void getAssetList(final OtcConfigResponse.TokenBean tokenBean) {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }
        String tokenId = tokenBean.getTokenId();

        TradeApi.SubTokenBalanceChange(tokenId, new SimpleResponseListener<AssetListResponse.BalanceBean>() {

            @Override
            public void onSuccess(AssetListResponse.BalanceBean response) {
                super.onSuccess(response);
                if (getUI() == null || !getUI().isAlive() || response == null)
                    return;
                if (response != null) {
                    getUI().updateAssettByToken(tokenBean, response.getFree());
                } else {
                    //因为API接口返回的资产列表，如果没有资产，则没有改币种资产信息，所以为空，代表没有查询到余额 默认按零资产处理
                    getUI().updateAssettByToken(tokenBean, "0");
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 获取资产
     *
     * @param tokenBean
     */
    protected void getAsset(final OtcConfigResponse.TokenBean tokenBean) {
        String tokenId = tokenBean.getTokenId();
        AssetApi.RequestTokenIdAsset(tokenId, new SimpleResponseListener<AssetDataResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(AssetDataResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<AssetDataResponse.ArrayBean> data = response.getArray();
                    if (data != null) {
                        if (data.size() > 0) {
                            AssetDataResponse.ArrayBean assetBean = data.get(0);
                            if (assetBean != null) {
                                getUI().updateAssettByToken(tokenBean, assetBean.getFree());
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }


    /**
     * 发布广告
     *
     * @param currentTokenBean
     * @param currentLegalCurrency
     * @param isFloatingPrice
     * @param price
     * @param num
     * @param minAmount
     * @param maxAmount
     * @param remark
     */
    public void publishAds(boolean isBuy, OtcConfigResponse.TokenBean currentTokenBean, OtcConfigResponse.CurrencyBean currentLegalCurrency, boolean isFloatingPrice, String price, String num, String minAmount, String maxAmount, String remark, String fundPwd) {
        if (!UserInfo.isLogin()) {
            return;
        }
        OtcAdsApi.publishAds(isBuy, currentTokenBean.getTokenId(), currentLegalCurrency.getCurrencyId(), isFloatingPrice, price, num, minAmount, maxAmount, remark, fundPwd, new SimpleResponseListener<OtcPublishAdResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("", "");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(OtcPublishAdResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    if (response.isSuccess()) {
                        ToastUtils.showLong(getActivity(), getString(R.string.string_otc_publish_success));
//                        IntentUtils.goOtcAds(getActivity());
                        getActivity().finish();
                        return;
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

}
